{% extends "base.html" %}

{% block title %}{{ document.title }} - AsciiDoc文档平台{% endblock %}

{% block extra_head %}
<style>
    .viewer-container {
        display: flex;
        height: calc(100vh - 120px);
    }
    
    .sidebar {
        width: 300px;
        background: #f8f9fa;
        border-right: 1px solid #dee2e6;
        overflow-y: auto;
    }
    
    .main-content {
        flex: 1;
        overflow-y: auto;
    }
    
    .toc-item {
        padding: 0.5rem 1rem;
        cursor: pointer;
        border-bottom: 1px solid #eee;
    }
    
    .toc-item:hover {
        background-color: #e9ecef;
    }
    
    .comment-section {
        background: #f8f9fa;
        padding: 1rem;
        border-top: 1px solid #dee2e6;
    }
    
    .comment {
        background: white;
        padding: 0.75rem;
        margin-bottom: 0.5rem;
        border-radius: 0.375rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    
    .comment-author {
        font-weight: bold;
        color: #0d6efd;
    }
    
    .comment-time {
        font-size: 0.875rem;
        color: #6c757d;
    }
    
    .search-highlight {
        background-color: yellow;
        padding: 2px 4px;
        border-radius: 3px;
    }
</style>
{% endblock %}

{% block content %}
<div class="viewer-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="p-3">
            <h5 class="mb-3">
                <i class="fas fa-list me-2"></i>
                目录
            </h5>
            <div id="tocContainer">
                <div class="text-center text-muted py-3">
                    <i class="fas fa-spinner fa-spin"></i>
                    加载目录...
                </div>
            </div>
            
            <hr>
            
            <h6 class="mb-2">
                <i class="fas fa-history me-1"></i>
                版本历史
            </h6>
            <div class="list-group list-group-flush">
                {% for version in versions %}
                <div class="list-group-item">
                    <small>
                        <strong>v{{ version.version }}</strong><br>
                        {{ version.timestamp[:10] }}<br>
                        <em>{{ version.changes }}</em>
                    </small>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 工具栏 -->
        <div class="bg-light p-3 border-bottom">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4 class="mb-0">{{ document.title }}</h4>
                    <small class="text-muted">
                        <i class="fas fa-user me-1"></i>{{ document.author }}
                        <i class="fas fa-clock ms-3 me-1"></i>{{ document.updated_at[:10] }}
                    </small>
                </div>
                <div class="btn-group">
                    <button class="btn btn-outline-primary btn-sm" onclick="toggleComments()">
                        <i class="fas fa-comments me-1"></i>评论
                    </button>
                    <button class="btn btn-outline-secondary btn-sm dropdown-toggle" 
                            data-bs-toggle="dropdown">
                        <i class="fas fa-download me-1"></i>导出
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="exportDoc('html')">HTML格式</a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportDoc('pdf')">PDF格式</a></li>
                        <li><a class="dropdown-item" href="#" onclick="exportDoc('epub')">EPUB格式</a></li>
                    </ul>
                </div>
            </div>
            
            <!-- 搜索框 -->
            <div class="mt-2">
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" id="searchInput" 
                           placeholder="在文档中搜索...">
                    <button class="btn btn-outline-secondary" type="button" onclick="searchInDocument()">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 文档内容 -->
        <div class="p-4">
            <iframe id="documentFrame" 
                    src="{{ url_for('static', filename='uploads/' + doc_id + '.html') }}" 
                    style="width: 100%; height: 600px; border: none;">
            </iframe>
        </div>
        
        <!-- 评论区 -->
        <div class="comment-section" id="commentsSection" style="display: none;">
            <h5 class="mb-3">
                <i class="fas fa-comments me-2"></i>
                评论 ({{ comments|length }})
            </h5>
            
            <div class="mb-3">
                <div class="input-group">
                    <input type="text" class="form-control" id="commentInput" 
                           placeholder="添加评论...">
                    <button class="btn btn-primary" type="button" onclick="addComment()">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
            
            <div id="commentsList">
                {% for comment in comments %}
                <div class="comment">
                    <div class="comment-author">{{ comment.author }}</div>
                    <div class="comment-time">{{ comment.timestamp[:16] }}</div>
                    <div class="comment-content">{{ comment.content }}</div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>

<script>
// 加载目录
function loadTOC() {
    const iframe = document.getElementById('documentFrame');
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    
    // 提取标题
    const headings = iframeDoc.querySelectorAll('h1, h2, h3, h4, h5, h6');
    let tocHTML = '';
    
    headings.forEach((heading, index) => {
        const level = parseInt(heading.tagName.substring(1));
        const indent = '  '.repeat(level - 1);
        const id = `heading-${index}`;
        heading.id = id;
        
        tocHTML += `
            <div class="toc-item" onclick="scrollToHeading('${id}')">
                ${indent}${heading.textContent}
            </div>
        `;
    });
    
    document.getElementById('tocContainer').innerHTML = tocHTML || 
        '<div class="text-muted text-center py-3">无目录</div>';
}

// 滚动到指定标题
function scrollToHeading(id) {
    const iframe = document.getElementById('documentFrame');
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    const element = iframeDoc.getElementById(id);
    
    if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
    }
}

// 切换评论区
function toggleComments() {
    const section = document.getElementById('commentsSection');
    section.style.display = section.style.display === 'none' ? 'block' : 'none';
}

// 搜索文档
function searchInDocument() {
    const query = document.getElementById('searchInput').value.trim();
    if (!query) return;
    
    const iframe = document.getElementById('documentFrame');
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    const body = iframeDoc.body;
    
    // 清除之前的高亮
    const highlights = body.querySelectorAll('.search-highlight');
    highlights.forEach(h => {
        const parent = h.parentNode;
        parent.replaceChild(document.createTextNode(h.textContent), h);
        parent.normalize();
    });
    
    // 搜索并高亮
    const walker = iframeDoc.createTreeWalker(
        body,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );
    
    let node;
    const textNodes = [];
    
    while (node = walker.nextNode()) {
        if (node.textContent.toLowerCase().includes(query.toLowerCase())) {
            textNodes.push(node);
        }
    }
    
    textNodes.forEach(textNode => {
        const text = textNode.textContent;
        const regex = new RegExp(`(${query})`, 'gi');
        const newText = text.replace(regex, '<span class="search-highlight">$1</span>');
        
        if (newText !== text) {
            const span = iframeDoc.createElement('span');
            span.innerHTML = newText;
            textNode.parentNode.replaceChild(span, textNode);
        }
    });
}

// 导出文档
function exportDoc(format) {
    window.location.href = `/api/document/{{ doc_id }}/export/${format}`;
}

// 添加评论
async function addComment() {
    const input = document.getElementById('commentInput');
    const content = input.value.trim();
    
    if (!content) {
        alert('请输入评论内容');
        return;
    }
    
    try {
        const response = await fetch(`/api/document/{{ doc_id }}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content: content,
                author: '当前用户'
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 添加评论到列表
            const commentsList = document.getElementById('commentsList');
            const comment = result.comment;
            
            commentsList.innerHTML += `
                <div class="comment">
                    <div class="comment-author">${comment.author}</div>
                    <div class="comment-time">${comment.timestamp}</div>
                    <div class="comment-content">${comment.content}</div>
                </div>
            `;
            
            input.value = '';
        }
    } catch (error) {
        alert('添加评论失败：' + error.message);
    }
}

// 页面加载完成后加载目录
window.addEventListener('load', function() {
    setTimeout(loadTOC, 1000); // 等待iframe加载完成
});
</script>
{% endblock %}
